package com.chinar.funds;

import static com.chinar.funds.until.PercentageParser.parsePercentage;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chinar.funds.Fund;
import com.chinar.funds.FundPosition;
import com.chinar.funds.FundPositionAdapter;

import org.json.JSONObject;
import org.json.JSONException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.json.JSONArray;


import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FundDetailActivity extends AppCompatActivity {
    private static final String TAG = "FundDetailActivity";
    private TextView tvFundCode, tvFundName, tvFundEstimate, tvFundNetValue;
    private RecyclerView rvPositions;
    private ProgressBar progressBar;
    private FundPositionAdapter positionAdapter;
    private List<FundPosition> positionList;
    private OkHttpClient client;
    private Fund fund;
    private TextView tvDetailSumChangeValue;

    Double sumChangeValue = 0.0;
    String changeUrl = "https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&invt=2&fields=f2,f3,f12,f14,f9&secids=";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fund_detail);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        initViews();

        // 获取传递的基金数据
        fund = (Fund) getIntent().getSerializableExtra("fund");
        if (fund != null) {
            displayFundInfo(fund);
            // 初始化OkHttpClient
            client = new OkHttpClient();
            // 加载基金持仓数据
            loadFundPositions();
        } else {
            Log.e(TAG, "基金数据为空");
            Toast.makeText(this, "基金数据为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void initViews() {
        tvFundCode = findViewById(R.id.tv_detail_fund_code);
        tvFundName = findViewById(R.id.tv_detail_fund_name);
        tvFundEstimate = findViewById(R.id.tv_detail_fund_estimate);
        tvFundNetValue = findViewById(R.id.tv_detail_fund_net_value);
        tvDetailSumChangeValue=findViewById(R.id.tv_detail_sum_change_value);
        rvPositions = findViewById(R.id.rv_positions);
        progressBar = findViewById(R.id.progress_bar);

        rvPositions.setLayoutManager(new LinearLayoutManager(this));
        positionList = new ArrayList<>();
        positionAdapter = new FundPositionAdapter(positionList);
        rvPositions.setAdapter(positionAdapter);
    }

    private void displayFundInfo(Fund fund) {
        tvFundCode.setText(fund.getCode());
        tvFundName.setText(fund.getName());
        tvFundEstimate.setText(fund.getEstimate());
        tvFundNetValue.setText(fund.getYesterdayNetValue());


            double estimate= Double.parseDouble(fund.getEstimate());
            double yesterdayNetValue= Double.parseDouble(fund.getYesterdayNetValue());
            if (estimate>yesterdayNetValue){
                tvFundEstimate.setTextColor(0xFFFF0000);
            }else if(estimate<yesterdayNetValue){
                tvFundEstimate.setTextColor(0xFF00FF00);
            }else {
                tvFundEstimate.setTextColor(0xFF000000);
            }


    }

    private void loadFundPositions() {
        // 显示进度条
        progressBar.setVisibility(View.VISIBLE);
        rvPositions.setVisibility(View.GONE);

        // 检查基金代码是否有效
        if (fund.getCode() == null || fund.getCode().isEmpty()) {
            Log.e(TAG, "基金代码为空");
            progressBar.setVisibility(View.GONE);
            Toast.makeText(this, "基金代码为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = "https://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code=" + fund.getCode() + "&topline=1000&year=&month=";

        Log.d(TAG, "请求URL: " + url);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                .addHeader("Accept-Encoding", "gzip,deflate, br")
                .addHeader("Connection", "keep-alive")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "网络请求失败", e);
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(FundDetailActivity.this, "获取数据失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d(TAG, "响应数据长度: " + responseData.length());
                    parseFundPositions(responseData);
                } else {
                    Log.e(TAG, "服务器响应错误: " + response.code());
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(FundDetailActivity.this, "获取数据失败，服务器响应: " + response.code(), Toast.LENGTH_LONG).show();
                    });
                }
            }
        });
    }

    private void parseFundPositions(String data) {
        Log.d(TAG, "开始解析数据，数据长度: " + data.length());
        // 清空旧数据
        positionList.clear();

        try {
            // 查找apidata部分
            Pattern pattern = Pattern.compile("var\\s+apidata=\\{(.*?)\\};", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(data);

            if (matcher.find()) {
                String jsonData = "{" + matcher.group(1) + "}";
                Log.d(TAG, "找到apidata部分，长度: " + jsonData.length());

                // 修复JSON解析问题
                jsonData = jsonData.replace("\\\"", "\"")
                        .replace("\\\\", "\\")
                        .replace("\\n", "")
                        .replace("\\r", "")
                        .replace("\\t", "");

                JSONObject jsonObject = new JSONObject(jsonData);
                String content = jsonObject.getString("content");
                Log.d(TAG, "content内容长度: " + content.length());

                // 解码HTML实体
                content = unescapeJava(content);

                // 使用Jsoup解析表格数据
                parseTableWithJsoup(content);
            } else {
                Log.e(TAG, "未找到apidata部分");
                // 尝试另一种方式查找content
                parseContentDirectly(data);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析错误", e);
            // 尝试直接解析content
            parseContentDirectly(data);
        } catch (Exception e) {
            Log.e(TAG, "解析数据时出错", e);
            runOnUiThread(() -> {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(FundDetailActivity.this, "解析数据失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            });
        }
    }

    private void parseContentDirectly(String data) {
        Log.d(TAG, "尝试直接解析content");
        try {
            Pattern contentPattern = Pattern.compile("\"content\"\\s*:\\s*\"([^\"]*)\"");
            Matcher contentMatcher = contentPattern.matcher(data);

            if (contentMatcher.find()) {
                String content = contentMatcher.group(1);
                Log.d(TAG, "直接找到content，长度: " + content.length());
                content = unescapeJava(content);
                parseTableWithJsoup(content);
            } else {
                Log.e(TAG, "直接解析也未找到content");
                // 打印部分数据用于调试
                Log.d(TAG, "数据预览: " + data.substring(0, Math.min(1000, data.length())));
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(FundDetailActivity.this, "无法找到数据内容", Toast.LENGTH_LONG).show();
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "直接解析content时出错", e);
            runOnUiThread(() -> {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(FundDetailActivity.this, "解析内容失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            });
        }
    }

    /**
     * 解码JavaScript字符串
     */
    private String unescapeJava(String escaped) {
        if (escaped == null) return null;

        // 处理常见的转义字符
        return escaped.replace("\\\"", "\"")
                .replace("\\\\", "\\")
                .replace("\\r", "\r")
                .replace("\\n", "\n")
                .replace("\\t", "\t")
                .replace("\\/", "/")
                .replace("\\'", "'");
    }

    private void parseTableWithJsoup(String content) {
        Log.d(TAG, "使用Jsoup解析表格数据，内容长度: " + content.length());

        List<FundPosition> tempList = new ArrayList<>();
        List<String> stockCodeList = new ArrayList<>();
        List<String> stockNameList = new ArrayList<>();
        List<String> latestPriceList = new ArrayList<>();
        List<String> changePercentList = new ArrayList<>();
        List<String> holdingSharesList = new ArrayList<>();
        List<String> changeValueList = new ArrayList<>();
        List<String> urlGetlatestCodeList = new ArrayList<>();



        try {
            Document doc = Jsoup.parse(content);
            Elements tables = doc.select("table");

            Log.d(TAG, "找到" + tables.size() + " 个表格");

            // 遍历所有表格
            for (Element table : tables) {
                Elements rows = table.select("tr");

                Log.d(TAG, "表格包含 " + rows.size() + " 行");

                // 跳过表头，从第二行开始处理
                for (int i = 1; i < rows.size(); i++) {
                    Element row = rows.get(i);
                    Elements cells = row.select("td");

                    Log.d(TAG, "第" + (i + 1) + "行包含 " + cells.size() + " 个单元格");

                    // 确保有足够的单元格（至少9个）
                    if (cells.size() >= 9) {
                        // 获取各列数据
                        String stockCode = cells.get(1).text().trim();       // 股票代码
                        stockCodeList.add(stockCode);
                        String stockName = cells.get(2).text().trim();       // 股票名称
                        stockNameList.add(stockName);
                        String holdingShares = cells.get(7).text().trim();   // 持股数
                        holdingSharesList.add(holdingShares);
                        String stockCodeParam = cells.get(1).select("a").first().attr("href");   // 股票代码参数

                        // 从链接中提取股票代码
                        String regex = "r/(\\d+\\.\\d+)";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(stockCodeParam);

                        // 查找匹配项
                        if (matcher.find()) {
                            // 提取匹配的数字部分
                            String number = matcher.group(1);
                            urlGetlatestCodeList.add(number);
                            // 发送请求获取最新价和涨跌幅


                            Log.d(TAG, "匹配到的数字是: " + number);
                        } else {
                            Log.d(TAG, "未找到匹配的数字");
                        }

                        Log.d(TAG, "添加持仓数据: " + stockCode);
                    } else {
                        Log.d(TAG, "行" + (i + 1) + " 单元格数量不足: " + cells.size());
                    }
                }
            }


            String numberStr=String.join(",",  urlGetlatestCodeList);
            try {
                OkHttpClient stockClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(changeUrl + numberStr)
                        .addHeader("User-Agent", "Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                        .build();

                Response response = stockClient.newCall(request).execute();
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseData).getJSONObject("data");
                    JSONArray diff_temp = jsonResponse.getJSONArray("diff");
                    for(int i = 0; i < diff_temp.length(); i++){
                        JSONObject diff = diff_temp.getJSONObject(i);
                        String latestPrice = String.valueOf(diff.get("f2"));

                        latestPriceList.add(latestPrice);
                        String changePercent = String.valueOf(diff.get("f3"));
                        if (!changePercent.equals("-")){
                            changePercent=changePercent+  "%";
                        }
                        changePercentList.add(changePercent);
                        changeValueList.add(calculateChangeValue(latestPrice, changePercent, holdingSharesList.get(i)));
                    }

                    // 检查返回数据是否有效
//                    if ( !jsonResponse.isNull("diff")) {
//                        // 获取f2和f3字段作为最新价和涨跌幅
//
//                        String changeValue = calculateChangeValue(latestPrice, changePercent, holdingShares);
//                        sumChangeValue=sumChangeValue+Double.parseDouble(changeValue);
//                        // 使用正确的数据创建FundPosition对象
//                        FundPosition position = new FundPosition(stockCode, stockName, latestPrice,
//                                changePercent, holdingShares, changeValue);
//                        tempList.add(position);
//                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取股票数据失败", e);
            }

            if  (stockCodeList.size() == stockNameList.size() && stockCodeList.size() == latestPriceList.size() &&
                    stockCodeList.size() == changePercentList.size() && stockCodeList.size() == holdingSharesList.size()) {
                for (int i = 0; i < stockCodeList.size(); i++) {
                                            FundPosition position = new FundPosition(stockCodeList.get(i),
                                                    stockNameList.get(i), latestPriceList.get(i),
                                                    changePercentList.get(i), holdingSharesList.get(i), changeValueList.get(i));

                        tempList.add(position);
                        sumChangeValue=sumChangeValue+Double.parseDouble(changeValueList.get(i));
                }

            }



            if (tables.isEmpty()) {
                Log.e(TAG, "未找到任何表格");
            }
        } catch (Exception e) {
            Log.e(TAG, "使用Jsoup解析数据时出错", e);
            runOnUiThread(() -> {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(FundDetailActivity.this, "Jsoup解析失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            });
            return;
        }

        Log.d(TAG, "总共解析到 " + tempList.size() + " 条数据");

        runOnUiThread(() -> {
            positionList.addAll(tempList);

            if (sumChangeValue>0){
                tvDetailSumChangeValue.setTextColor(0xFFFF0000);
            }else if(sumChangeValue<0){
                tvDetailSumChangeValue.setTextColor(0xFF00FF00);
            }else {
                tvDetailSumChangeValue.setTextColor(0xFF000000);
            }
            tvDetailSumChangeValue.setText(String.format("%.2f", sumChangeValue)+"万元");


            positionAdapter.notifyDataSetChanged();
            progressBar.setVisibility(View.GONE);
            rvPositions.setVisibility(View.VISIBLE);

            if (tempList.isEmpty()) {
                Toast.makeText(FundDetailActivity.this, "未解析到有效数据", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(FundDetailActivity.this, "成功加载 " + tempList.size() + "条持仓数据", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String calculateChangeValue(String latestPriceStr, String changePercentStr, String holdingSharesStr) {
        try {
            // 处理空值或无效值
            if (latestPriceStr == null || latestPriceStr.isEmpty() ||
                    changePercentStr == null || changePercentStr.isEmpty() ||
                    holdingSharesStr == null || holdingSharesStr.isEmpty()) {
                return "0.00";
            }

            // 清理数据
            latestPriceStr = latestPriceStr.trim().replace(",", "");
            holdingSharesStr = holdingSharesStr.trim().replace(",", "");
            changePercentStr = changePercentStr.trim().replace("%", "").replace(",", "");

            // 检查是否是有效数字
            if (!isNumeric(latestPriceStr) || !isNumeric(changePercentStr) || !isNumeric(holdingSharesStr)) {
                return "0.00";
            }

            double latestPrice = Double.parseDouble(latestPriceStr);
            double holdingShares = Double.parseDouble(holdingSharesStr);
            // 去除涨跌幅中的%符号并转换为小数
            double changePercent = Double.parseDouble(changePercentStr) / 100.0;

            // 防止除零错误
            if (changePercent == -1) { // 涨跌幅为-100%
                return "0.00";
            }

            // 计算涨跌值:最新价/(1+涨跌幅)*涨跌幅持有量
            double changeValue = (latestPrice / (1 + changePercent)) * changePercent * holdingShares;

            // 防止返回NaN
            if (Double.isNaN(changeValue)) {
                return "0.00";
            }

            return String.format("%.2f", changeValue);
        } catch (Exception e) {
            Log.e(TAG, "计算涨跌值时出错: latestPrice=" + latestPriceStr +
                    ", changePercent=" + changePercentStr, e);
            return "0.00";
        }
    }


    private boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}